import { defineStore } from 'pinia';
import { login, logout, getUserInfo } from '@/api/auth';

export const useUserStore = defineStore('user', {
  state: () => ({
    token: uni.getStorageSync('token') || '',
    userInfo: null
  }),
  
  actions: {
    // 登录
    async loginAction(loginForm) {
      try {
        const res = await login(loginForm);
        const { token } = res.data;
        this.token = token;
        uni.setStorageSync('token', token);
        return res;
      } catch (error) {
        throw error;
      }
    },
    
    // 登出
    async logoutAction() {
      try {
        await logout();
        this.token = '';
        this.userInfo = null;
        uni.removeStorageSync('token');
        uni.reLaunch({
          url: '/pages/login/index'
        });
      } catch (error) {
        throw error;
      }
    },
    
    // 获取用户信息
    async getUserInfoAction() {
      try {
        const res = await getUserInfo();
        this.userInfo = res.data;
        return res.data;
      } catch (error) {
        throw error;
      }
    }
  }
}); 